﻿#include "lah/hand_StaticLib.h"

PyObject* Init_Hand_Model() {
    //加载numpy库
	import_array();
	PyRun_SimpleString("import sys");
    QString t = "sys.path.append('" + QDir::currentPath()  + "/script')";
    PyRun_SimpleString(t.toStdString().c_str());

	PyObject* pModule = PyImport_ImportModule("infer");
	if (pModule == NULL) {
		cout << "pModule not found" << endl;
	}

    //模型加载
	PyObject* pFunc_load = PyObject_GetAttrString(pModule, "load_model");
	if (pFunc_load == NULL || PyCallable_Check(pFunc_load) == NULL) {
		cout << "pFunc_load not found!" << endl;
		return 0;
	}
	PyObject_CallObject(pFunc_load, NULL);
    //准备推理模型
	PyObject* pInfer = PyObject_GetAttrString(pModule, "infer_image");
	if (pInfer == NULL || PyCallable_Check(pInfer) == NULL) {
		cout << "pInfer not found!" << endl;
		return 0;
	}
	Py_DECREF(pModule);
	Py_DECREF(pFunc_load);
	return pInfer;
}

cv::Mat Hand_Infer(cv::Mat img, PyObject* pInfer,int *res)
{
	PyArrayObject* array_com = NULL;
	PyObject* pRet = NULL;
	npy_intp dims[] = { img.rows, img.cols, img.channels() };

	PyObject* pValue = PyArray_SimpleNewFromData(3, dims, NPY_UINT8, img.data);
	PyObject* pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, pValue);
	pRet = PyObject_CallObject(pInfer, pArgs);
	Py_DECREF(pValue);
	Py_DECREF(pArgs);

	//PyArrayObject* array_com;
	*res = -1;
	PyArray_OutputConverter(PyList_GetItem(pRet, 0), &array_com);
	npy_intp* shape = PyArray_SHAPE(array_com);
	Mat com(shape[0], shape[1], CV_8UC3, PyArray_DATA(array_com));
	PyArg_Parse(PyList_GetItem(pRet, 1),"i",res);
	return com;
}

